<template>
	<view class="container">
		<u-navbar :is-fixed='true' :title-bold='true' :border-bottom='false' title='咨询问卷'></u-navbar>

		<view class="top" v-if="type==2">
			<view class="item" @click="t_index=0" :class="t_index==0?'on':''">
				<span>1.{{initdata[0].title||''}}</span>
				<view class="b"></view>
			</view>
			<view class="item " @click="t_index=1" :class="t_index==1?'on':''">
				<view class="a"></view><span>2.{{initdata[1].title||''}}</span>
				<view class="b"></view>
			</view>
			<view class="item last" @click="t_index=2" :class="t_index==2?'on':''">
				<view class="a"></view><span>3.{{initdata[2].title||''}}</span>
			</view>
		</view>

		<scroll-view scroll-y="true" :scroll-top="scrollTop" @scroll="scroll" class="main">
			<view class="form">
				<text v-if="type==2" class="title">{{t_index==0?'基本资料':t_index==1?'现病史':'既往史'}}</text>
				<u-form :model="form" ref="uForm" label-position='top'>
					<u-form-item prop="member_id" v-show="t_index==0" :border-bottom='false'>
						<view class="fixed" @click="show=true">
							<view class="t">
								<image src="../../../static/img/addmember.png" mode="widthFix"></image>
								<span>请选择成员</span>
							</view>
							<view :style="{color:patient?'':'#CCCCCC'}">
								{{patient||'请选择成员'}}
								<u-icon style="margin-left: 16rpx;" name="arrow-right" color="#B6B6B6"
									size="26"></u-icon>
							</view>
						</view>
					</u-form-item>

					<!-- type  类型:1=单选,2=多选,3=输入框,4=文本域,5=图片,6=输入框+图片 -->
					<u-form-item v-for="(itm,idx) in initdata[t_index].modules"
						:label="itm.type=='2'?itm.title+'(多选)':itm.title" :border-bottom='false'
						:required='itm.required==1'>

						<u-radio-group v-model="itm.radio" v-show="itm.type=='1'" width='50%' @change="groupChange()">
							<u-radio v-for="(item, index) in itm.content" :key="index"
								:name="JSON.stringify({'id':itm.id,'value':item,'type':itm.type,'title':itm.title})">
								{{ item }}
							</u-radio>
						</u-radio-group>

						<u-checkbox-group v-show="itm.type=='2'" width='50%' @change="checkboxChange">
							<u-checkbox v-model="item.checked" @change="checkChange"
								v-for="(item, index) in itm.content" :key="index"
								:name="JSON.stringify({'idx':idx,'value':item.name})"
								shape="circle">{{item.name}}</u-checkbox>
						</u-checkbox-group>
						<u-field label-width='0' v-show="itm.type=='2' && itm.other " placeholder="请填写"
							@blur='onblur(itm)' v-model="itm.contentext" />

						<u-field label-width='0' v-show="itm.type=='3'" @blur='onblur(itm)' v-model="itm.contentext" />

						<view v-show="itm.type=='4'" class="remake">
							<u-input height='200' :maxlength='300' type="textarea" placeholder="请填写" @blur='onblur(itm)'
								v-model="itm.contentext" />
						</view>

						<view v-show="itm.type=='5'" @click="onbefore(itm)">
							<u-upload :width='150' :height="150" ref="uUpload" :action="action" :show-progress='false'
								:max-size="5 * 1024 * 1024" max-count="4" @on-change='uploadimg' @on-remove='removeimg'
								:form-data='formdata'>
							</u-upload>
						</view>

						<view v-show="itm.type=='6'">
							<u-field label-width='0' @blur='onblur(itm)' v-model="itm.contentext" />
							<view @click="onbefore(itm)">
								<u-upload :width='150' :height="150" ref="uUpload" :action="action"
									:show-progress='false' :max-size="5 * 1024 * 1024" max-count="4"
									@on-change='uploadimg' @on-remove='removeimg' :form-data='formdata'>
								</u-upload>
							</view>
						</view>

						<view v-show="itm.type=='7'" @click="picker=true,indx=idx,onbefore(itm)"
							class="u-flex u-row-between">
							{{itm.content||'请选择'}}
							<uni-icons type="right" size='15'></uni-icons>
						</view>

					</u-form-item>
				</u-form>
			</view>
		</scroll-view>
		<!-- 操作 -->
		<view class="btu">
			<view v-if="type==2" class="event">
				<view class="back" v-if="t_index>0" @click="--t_index">上一步</view>
				<view class="next" @click="next()">保存，{{t_index==2?'预览':'下一步'}} </view>
			</view>
			<view v-else class="btn" @click.stop="save()">
				保存，预览
			</view>
		</view>

		<!-- 提示 -->
		<u-toast ref="uToast" />
		<!-- 选择患者 -->
		<u-popup v-model="show" mode="bottom">
			<view class="popup">
				<p style="opacity: 0.6;">已绑定{{docker.nickname||''}}的成员({{bindPeople}}/{{totalPeople}})</p>
				<u-line margin='30rpx 0' />
				<view v-for="(item,index) in list" :key="index" @click="chooseMember(item)">
					<view class="member p-m">
						<view class="member">
							<view class="avatar">
								{{item.username.substring(item.username.length-1),1}}
							</view>
							<view style="margin-left: 16rpx;">
								<view style="font-size: 16px;">{{item.username}}</view>
								<view style="opacity: 0.6;">有效期至 {{item.end_time}}</view>
							</view>
						</view>
						<image v-show="form.member_id==item.id" style="height: 17px;width: 17px;"
							src="@/static/icon/sure.png" mode="widthFix"></image>
					</view>

					<u-line margin='30rpx 0 30rpx 146rpx' />
				</view>

				<view class="member bding">
					<image @click="goTo('/sub/center/mine/chooseUmbrella?docker_id='+docker.id)" class="m-img"
						src="@/static/icon/add.png"></image>
					<view style="opacity: 0.6;">
						还可绑定{{totalPeople-bindPeople}}个成员
					</view>
				</view>
			</view>
		</u-popup>
		<u-picker v-model="picker" :endYear='startTime' @confirm="confirmPicker()" mode="time"></u-picker>
	</view>
</template>

<script>
	import {
		adviceIndex,
		selectMember,
		addAdvice
	} from '../../../api/index.js'
	export default {
		data() {
			return {
				t_index: 0,
				scrollTop: 0,
				old: {
					scrollTop: 0
				},
				list: [],
				patient: '',
				show: false,
				fileList: [],
				action: '',
				formdata: new Object(),
				images: [],
				form: {},
				docker: {},
				bindPeople: 0,
				totalPeople: 0,
				initdata: [{
					modules: [{
						content: []
					}]
				}],
				type: '',
				picker: false,
				startTime: new Date().getFullYear(),
				module: "",
				indx: 0
			}
		},
		watch: {
			images: {
				handler(newdata, old) {
					// console.log(newdata,'图片');
					let src = ''
					newdata.forEach(item => {
						src = src + item.src + ','
					})
					src = src.substring(0, src.length - 1)
					let obj = {
						id: this.module.id,
						title: this.module.title,
						type: this.module.type,
						images: src,
					}
					this.imageChange(obj)
				}
			},

		},
		onLoad(e) {
			this.docker.id = e.id
			this.type = e.type
			this.action = this.ws.upload;
			this.init(this.docker.id)
		},
		onShow() {
			this.getMember()
		},
		methods: {
			goTo(url) {
				uni.navigateTo({
					url: url
				})
			},
			init(id) {
				let that = this
				that.form.doctor_id = id
				that.form.type = Number(that.type)
				that.form.content = []
				that.form.content.push({
					'cate_id': 1,
					'detail': []
				})
				that.form.content.push({
					'cate_id': 2,
					'detail': []
				})
				that.form.content.push({
					'cate_id': 3,
					'detail': []
				})
				that.$store.state.zixunPreview = that.form

				adviceIndex({
					'doctor_id': id,
					'type': that.type
				}).then(res => {
					if (res.code == 0) {
						that.$refs.uToast.show({
							title: res.msg,
							callback: () => {
								uni.navigateTo({
									url: '/sub/session-info/thank?id=' + id
								})
							}
						})
					} else {
						that.docker = res.data.doctor
						let arr = res.data.template
						if (that.type == 1) {
							that.initdata[0].modules = res.data.template
							arr = that.initdata
						}
						arr.forEach(e => {
							e.modules.forEach(itm => {
								if (itm.type == 2) {
									itm.content = Object.keys(itm.content).map(key => ({
										checked: false,
										name: itm.content[key]
									}));
								}
							})
						})
						that.initdata = arr
					}

				})

				this.st
			},

			// 获取患者
			getMember() {
				let that = this
				selectMember({
					'doctor_id': that.docker.id
				}).then(res => {
					if (res && res.code == 1) {
						that.bindPeople = res.data.bindPeople
						that.totalPeople = res.data.totalPeople
						that.list = res.data.memberList;
					} else {
						that.$refs.uToast.show({
							title: res.msg
						})
					}
				})
			},
			confirmPicker(e) {
				let str = e.year + '-' + e.month + '-' + e.day
				let obj = {
					id: this.module.id,
					title: this.module.title,
					type: this.module.type,
					value: str,
				}

				this.initdata[this.t_index].modules[this.indx].content = str
				this.groupChange(JSON.stringify(obj))
			},
			next() {
				if (!this.form.member_id) {
					this.$refs.uToast.show({
						title: '请选择成员',
						type: 'error'
					})
					return;
				}
				// 校验必填项
				let arr = [];

				this.form.content[this.t_index].detail.forEach(i => {
					arr.push(i.id)
				})

				for (let i in this.initdata[this.t_index].modules) {
					let m = this.initdata[this.t_index].modules[i]
					if (m.required == 1) {
						// type  类型:1=单选,2=多选,3=输入框,4=文本域,5=图片,6=输入框+图片
						if (arr.indexOf(m.id) == -1 && !m.contentext) {
							// console.log(m,arr);
							this.$refs.uToast.show({
								title: '请补充' + m.title,
								type: 'error'
							})
							return;
						}

					}
				}
				// -----------------

				if (this.t_index < 2) {
					// 解决view层不同步的问题
					this.scrollTop = this.old.scrollTop
					this.$nextTick(function() {
						this.scrollTop = 0
					});
					this.t_index++
				} else {
					this.submit()
				}
			},
			//预览 提交问卷  
			submit() {
				let that = this
				uni.navigateTo({
					url: '/sub/center/mine/zixunPreview?type=' + this.type
				})
				// addAdvice(that.form).then(res=>{
				// 	if(res.code==1){
				// 		that.$refs.uToast.show({
				// 			title: res.msg,
				// 			type: 'primary',
				// 		})
				// 		that.ws.tochat(res.data.session_id)

				// 	}else{
				// 		that.$refs.uToast.show({
				// 			title: res.msg
				// 		})
				// 	}
				// })
			},
			save() {
				if (!this.form.member_id) {
					this.$refs.uToast.show({
						title: '请选择成员',
						type: 'error'
					})
					return;
				}

				let arr = [];

				this.form.content[this.t_index].detail.forEach(i => {
					arr.push(i.id)
				})

				for (let i in this.initdata[this.t_index].modules) {
					let m = this.initdata[this.t_index].modules[i]
					if (m.required == 1) {
						// type  类型:1=单选,2=多选,3=输入框,4=文本域,5=图片,6=输入框+图片
						if (arr.indexOf(m.id) == -1 && !m.contentext) {
							// console.log(m,arr);
							this.$refs.uToast.show({
								title: '请补充' + m.title,
								type: 'error'
							})
							return;
						}

					}
				}

				this.submit()
			},
			chooseMember(item) {
				if (this.form.member_id == item.id) {
					this.form.member_id = ''
					this.form.protect_id = ''
					this.patient = ''
				} else {
					this.form.member_id = item.id
					this.form.protect_id = item.protect_id
					this.patient = item.username
					this.show = false
				}

			},
			// 多选
			checkChange(e) {
				let obj = JSON.parse(e.name),
					data = {},
					modules = this.initdata[this.t_index].modules[obj.idx];
				if (obj.value == '其他') {
					modules.other = e.value
					if (!e.value) {
						modules.contentext = ''
					}
				}

				if (obj.value == '无') {
					modules.content.forEach((item, index) => {
						if (index > 0) {
							item.checked = false
						}
					})
					modules.other = ''
					modules.contentext = ''
				} else {
					modules.content[0].checked = false
				}

				if (!e.value) {
					modules.checkboxtext = modules.checkboxtext.replace(obj.value, '')
					data.id = modules.id
					data.value = modules.checkboxtext
					data.type = modules.type
					data.title = modules.title
					this.groupChange(JSON.stringify(data))
					this.$forceUpdate()
				}

			},
			checkboxChange(e) {
				let str = '',
					idx, data = {},
					modules;
				if (e.length > 0) {
					e.forEach(item => {
						let obj = JSON.parse(item)
						idx = obj.idx
						if (obj.value != '其他') {
							str = str + obj.value + ','
						}
					})
					str = str.substring(0, str.length - 1)
					modules = this.initdata[this.t_index].modules[idx]
					modules.checkboxtext = str
					data.id = modules.id
					data.value = str
					data.type = modules.type
					data.title = modules.title
					this.groupChange(JSON.stringify(data))
					this.$forceUpdate()
				}

			},

			// 单选
			groupChange(e) {
				let obj = JSON.parse(e)
				let a = this.form.content[this.t_index].detail.every((item, index, array) => {
					if (item.id == obj.id) {
						item.value = obj.value
						return false;
					}
					return true;
				});
				if (a) {
					this.form.content[this.t_index].detail.push(obj)
				}
				console.log(this.form);
				this.$store.state.zixunPreview = this.form
			},
			// 图片
			imageChange(obj) {
				let a = this.form.content[this.t_index].detail.every((item, index, array) => {
					if (item.id == obj.id) {
						item.images = obj.images
						if (!item.value) {
							item.value = ''
						}
						return false;
					}
					return true;
				});
				if (a) {
					this.form.content[this.t_index].detail.push(obj)
				}

			},
			// 输入
			onblur(e) {
				let obj = {
					'id': e.id,
					'value': e.contentext,
					'type': e.type,
					'title': e.title
				}
				if (e.type == 2 && e.checkboxtext) {
					obj.value = e.checkboxtext + ',' + e.contentext
				}

				this.form = this.$store.state.zixunPreview
				this.groupChange(JSON.stringify(obj))
			},
			// 图片上传
			uploadimg(res, index, lists) {
				res = JSON.parse(res.data);
				if (res.code == 1) {
					let src = this.ws.imgUrl(res.data.fullurl)

					this.images.push({
						index: index,
						src: src
					})
				}
			},
			removeimg(index, lists, name) {
				this.images.forEach((item, idx) => {
					if (item.index == index) {
						let a = this.images.splice(idx, 1)
					}
				})

			},
			onbefore(e) {
				this.module = e
			},

			scroll: function(e) {
				this.old.scrollTop = e.detail.scrollTop
			},
		}
	}
</script>

<style lang="less">
	.container {
		background-color: #FFF;
		height: 100vh;

		.top {
			display: flex;
			width: 100%;
			padding: 30rpx;
			align-items: center;
			justify-content: flex-start;
			color: #878787;

			.item {
				background-color: #EDEDED;
				display: flex;
				align-items: center;
				flex: 1;
				position: relative;
				line-height: 32px;
				background: #EDEDED;
				color: #878787;
				height: 32px;
				padding: 10rpx 16px;

				span {
					position: relative;
					z-index: 99;
				}

				.a {
					border: 16px solid #EDEDED;
					border-left-color: transparent;
					position: absolute;
					left: -16px;
					top: 0px;
				}

				.b {
					border: 16px solid #fff;
					border-left-color: #EDEDED;
					position: absolute;
					right: -6px;
					top: 0px;
				}

			}

			.on {
				background: #6EC9E1;
				color: #fff;

				.a {
					border: 16px solid #6EC9E1;
					border-left-color: transparent;
				}

				.b {
					border-left-color: #6EC9E1 !important;
				}
			}

			.last {
				padding: 0;
				padding-left: 8px;

				.b {
					border: 16px solid #FFF;
				}
			}

		}

		.main {
			.form {
				padding: 30rpx 50rpx;
			}

			max-height: 70vh;

			.title {
				font-size: 18px;
			}

			.fixed {
				display: flex;
				justify-content: space-between;
				align-items: center;
				border-radius: 6px;
				background: #F4FAF9;
				padding: 20rpx;

				.t {
					image {
						width: 34px;
						margin-right: 20rpx;
					}

					display: flex;
					align-items: center;
				}
			}
		}

		.remake {
			background-color: #F6F6F6;
			border-radius: 20rpx;
			padding: 20rpx;
		}

		.popup {
			height: 50vh;
			padding: 40rpx 0;

			p {
				padding: 0 40rpx;
			}

		}

		.p-m {
			justify-content: space-between;
			padding: unset !important;
			padding-right: 40rpx !important;
		}

		.avatar {
			background-color: #6EC9E1;
			border-radius: 50%;
			height: 45px;
			width: 45px;
			text-align: center;
			line-height: 45px;
			font-size: 16px;
			color: #FFF !important;
		}

		.bding {
			position: sticky;
			bottom: 20rpx;
			background-color: #FFF;
		}

		.member {
			display: flex;
			padding: 0 40rpx;
			align-items: center;

			.m-img {
				height: 42px;
				width: 42px;
				margin-right: 20rpx;
			}
		}

		.event {
			display: flex;
			justify-content: space-between;
			align-items: center;
			width: 100%;
			padding: 0 30rpx;

			view {
				height: 60px;
				border-radius: 4px;
				line-height: 60px;
				text-align: center;
			}

			.back {
				background-color: #EDF8FA;
				color: #6EC9E1;
				min-width: 40%;
			}

			.next {
				background-color: #6EC9E1;
				color: #FFF;
				width: 100%;
				margin-left: 30rpx;
			}
		}

		.btu {
			width: 100%;
			position: fixed;
			bottom: 2vh;
			z-index: 999;
			display: flex;
			justify-content: center;
		}

	}
</style>